package com.cloud.netty.ProtocolTcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;


/**
 * @program: netty
 * @description:
 * @author: Cloud
 * @create: 2022/4/14 14:20:11
 */
public class ProClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        byte[] content = msg.getContent();
        int len = msg.getLen();
        System.out.println("服务端信息如下:");
        System.out.println("长度: " + len);
        System.out.println("内容: " + new String(content, CharsetUtil.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 1; i++) {
            String mes = "今天天气热,吃冰棒!";
            byte[] content = mes.getBytes(CharsetUtil.UTF_8);
            System.out.println("content.length = " + content.length);
            System.out.println("mes.length() = " + mes.length());
            // 这里的长度应该为content的长度及转成byte数组的长度，因为传的byte数组的，不是mes（String字符串）的长度
            int length = content.length;
            ctx.writeAndFlush(new MessageProtocol(length,content));
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常！");
        ctx.close();
    }
}
